﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperKit
{
    class FastRename : CommandExecutor {
        private const int TYPE_RENAME = 0; // 对自身进行更名
        private const int TYPE_RENAME_DIRECTORY = 1; // 自身是一个目录，对目录以下的子文件进行更名
        private string Plan { get; set; }
        private int TypeId { get; set; }

        private const string PLAN_GALGAME = "Galgame";
        private const string PLAN_GALGAME_REVERSE = "GalgameReverse";

        public FastRename(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
        }

        public override void Execute() {
            base.Execute();
            Plan = Arg.GetParameter("-plan");
            TypeId = Arg.TypeId;

            if (TypeId == TYPE_RENAME) {
                RenamePath(FilePath);
            }else {
                RenameDirectory(FilePath);
            }

            
            
        }

        private void RenameDirectory(string filePath) {
            if (!Directory.Exists(filePath)) {
                Error("目录并不存在：{0}", filePath);
                return;
            }
            var dir = new DirectoryInfo(filePath);
            var files = dir.GetFiles();
            foreach(var i in files) {
                RenamePath(i.FullName);
            }
            var dirs = dir.GetDirectories();
            foreach(var i in dirs) {
                RenameDirectory(i.FullName);
            }
            // 最后对目录自身进行更名
            //RenamePath(filePath);
        }

        private void RenamePath(string filePath) {
            var adjust = Adjust(Path.GetFileName(filePath));
            if (Kit.IsEmpty(adjust)) {
                return;
            }
            var adjustPath = Path.Combine(Path.GetDirectoryName(filePath), adjust);

            if (File.Exists(adjustPath)) {
                Flush("文件已经存在：{0}", adjustPath);
                return;
            }
            File.Move(filePath, adjustPath);
            Flush("AdjustName:\r\n{0}\r\n{1}", filePath, adjustPath);
        }

        private string Adjust(string origin) {
            if (Kit.IsEqual(PLAN_GALGAME, Plan)) {
                return OnAdjustGalgame(origin);
            }else if (Kit.IsEqual(PLAN_GALGAME_REVERSE, Plan)) {
                return OnAdjustGalgameReverse(origin);
            } else {
                Error("指定的PLAN并不存在：{0}", Plan);
                return Kit.EMPTY;
            }
            
        }

        private string OnAdjustGalgameReverse(string origin) {
            var forbid = ReplacerDict.ReverseName(origin, ReplacerDict.ForbidWords);
            return forbid;
        }

        private string OnAdjustGalgame(string origin) {
            var clear = ReplacerDict.AdjustName(origin, ReplacerDict.GalgameReplacer);
            var forbid = ReplacerDict.AdjustName(origin, ReplacerDict.ForbidWords);
            return forbid;
        }
    }
}
